package org.wiztools.te.plugin;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

import org.wiztools.te.TEMod;
import org.wiztools.te.TEProcess;

public class GoTo implements TEProcess{
	private TEMod tem;
	private Container ct;
	private JTextField jtf;
	private JButton jb;
	
	public void setTEMod(TEMod tem){
		this.tem = tem;
	}
	
	public void init(){
		ct = new JPanel();
		ct.setLayout(new BorderLayout());
		ActionListener al = new ActionListener(){
				public void actionPerformed(ActionEvent ae){
					String str = tem.getText();
					int line_no = 0;
					try{
						line_no = Integer.parseInt(jtf.getText());
					}
					catch(NumberFormatException nfe){
						JOptionPane.showMessageDialog(tem.getJD(), "Please enter number", "Please enter number", JOptionPane.ERROR_MESSAGE);
						return;
					}
					int i = 0, tmp = 0;
					int newline_count = 0;
					
					if(line_no>tem.getLineCount()){
						tmp = str.lastIndexOf("\n");
						tmp++;
						Toolkit.getDefaultToolkit().beep();
					}
					else if(line_no<1){
						tmp = 0;
						Toolkit.getDefaultToolkit().beep();
					}
					else{
						while(newline_count<line_no){
							tmp = i;
							i = str.indexOf("\n", i);
							i++;
							newline_count++;
						}
					}
					tem.setCaretPosition(tmp++);
					tem.closeDialog();
					tem.requestFocus();
				}
			};
		jtf = new JTextField(15);
		jtf.addActionListener(al);
		ct.add(jtf, BorderLayout.CENTER);
		jb = new JButton("Go!");
		jb.addActionListener(al);
		ct.add(jb, BorderLayout.EAST);
	}
	
	public void action(){
		tem.dispDialog(ct, "Go To Line:");
		jtf.selectAll();
	}
	
	public void destroy(){
		// do nothing!
	}
}
